from app import db
from datetime import datetime

class Playlist(db.Model):
    __tablename__ = 'playlists'

    playlist_id = db.Column(db.String(36), primary_key=True)
    user_id = db.Column(db.String(36), db.ForeignKey('users.user_id'), nullable=False)
    name = db.Column(db.String(100), nullable=False, default='我的歌单')
    description = db.Column(db.Text)
    cover_url = db.Column(db.String(255))
    is_public = db.Column(db.Boolean, default=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    songs = db.Column(db.JSON)

    # 与用户的关系
    owner = db.relationship('User', back_populates='playlists')

    def __repr__(self):
        return f'<Playlist {self.name} by {self.user_id}>'

    def to_dict(self):
        return {
            'playlist_id': self.playlist_id,
            'name': self.name,
            'description': self.description,
            'cover_url': self.cover_url,
            'is_public': self.is_public,
            'song_count': len(self.songs) if self.songs else 0,
            'created_at': self.created_at.isoformat(),
            'updated_at': self.updated_at.isoformat()
        }